package kr.hkit.masan_alarm;

import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Masan_cancel extends Activity {
	String mRingTone ="";
	MediaPlayer mMediaPlayer = null;
	Vibrator vibe = null;
	PowerManager.WakeLock wl = null;
	PowerManager pm;
	Calendar calendar;
	Button btn;
	LinearLayout up, down;
	TextView tv;
	
	boolean startFlag = false;
	private NotificationManager nm = null;
	private AlarmManager mManager = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_cancel);
        
        pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
		int vibrate = getIntent().getIntExtra("vibrate", 0);
		
		mRingTone = getIntent().getStringExtra("ringtone");
		if (mRingTone == null || mRingTone.equals("")) {
			mRingTone = RingtoneManager.getValidRingtoneUri(this).toString();
			if (mRingTone == null) mRingTone = "";
		}
		
		showNotification(R.drawable.ic_launcher, "좋은 아침!~", mRingTone, vibrate);
				
        ///////////////////////////////////////
        btn = (Button) findViewById(R.id.btn_cancel);
        btn.setVisibility(Button.GONE);
        btn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mMediaPlayer != null) {
					mMediaPlayer.stop();
				}
				if (vibe != null){
					vibe.cancel();
				}
				mMediaPlayer = null;
				nm.cancel(12345);
				finish();
			}
		});
        
        tv = (TextView) findViewById(R.id.basket);
		
		findViewById(R.id.item_1).setOnTouchListener(mTouchListener);
		findViewById(R.id.item_2).setOnTouchListener(mTouchListener);
		findViewById(R.id.item_3).setOnTouchListener(mTouchListener);
		
		findViewById(R.id.up_linear).setOnDragListener(mDragListener);
		findViewById(R.id.down_linear).setOnDragListener(mDragListener);
	}	
	
	View.OnTouchListener mTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				ClipData clip = ClipData.newPlainText("", "");
				v.startDrag(clip, new CanvasShadow(v, (int)event.getX(), (int)event.getY()), v, 0);
				v.setVisibility(View.INVISIBLE);
				return true;
			}
			return false;
		}
	};
	
	class CanvasShadow extends View.DragShadowBuilder{
		int mWidth, mHeight;
		int mX, mY;
		public CanvasShadow(View v, int x, int y) {
			super(v);
			mWidth = v.getWidth();
			mHeight = v.getHeight();
			mX = x;
			mY = y;
		}
		
		@Override
		public void onProvideShadowMetrics(Point shadowSize,
				Point shadowTouchPoint) {
			shadowSize.set(mWidth, mHeight);
			shadowTouchPoint.set(mX, mY);
		}
		
		@Override
		public void onDrawShadow(Canvas canvas) {
			super.onDrawShadow(canvas);
		}
	}

	View.OnDragListener mDragListener = new View.OnDragListener() {
		@Override
		public boolean onDrag(View v, DragEvent event) {
			switch(event.getAction()){
			case DragEvent.ACTION_DRAG_STARTED:
				return true;
			case DragEvent.ACTION_DRAG_ENTERED:
				return true;
			case DragEvent.ACTION_DRAG_EXITED:
				return true;
			case DragEvent.ACTION_DROP:
				View view = (View) event.getLocalState();
				ViewGroup parent = (ViewGroup) view.getParent();
				parent.removeView(view);
				LinearLayout newparent = (LinearLayout) v;
				newparent.addView(view);
				view.setVisibility(view.VISIBLE);
				btn.setVisibility(Button.VISIBLE);
				tv.setVisibility(TextView.INVISIBLE);
				Toast.makeText(getApplicationContext(), "Ok, 화이팅", Toast.LENGTH_SHORT).show();
				return true;
			case DragEvent.ACTION_DRAG_ENDED:
				if(event.getResult() == false){
					((View)(event.getLocalState())).setVisibility(View.VISIBLE);
				}
				return true;
			}
			return false;
		}
	};
	
	
	 @Override
	protected void onResume() {
		super.onResume();
		if (!pm.isScreenOn()) {
			wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "MasanAlarm");
			wl.acquire();
			this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
										WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
										WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		}
	}
	 
	@Override
	 public void onDestroy() {
		 super.onDestroy();
		 nm = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
		 nm.cancelAll();
		 
		 Masan_info.startFirstAlarm(this);
	 }
	
	private void showNotification(int statusBarIconID, 
			String statusBatTextID, String ringtone, int vibrate){
		nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
		CharSequence from = "일어나요~";
		CharSequence message = "오늘도 화이팅^^";
		
		Intent intent = new Intent(this, Masan_cancel.class);
		PendingIntent theappIntent = PendingIntent.getActivity(this, 12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);		
		
		Notification notifi = new Notification.Builder(Masan_cancel.this)
		.setTicker(null)
		.setContentTitle(from)
		.setContentText(message)
		.setSmallIcon(R.drawable.ic_launcher)
		.setWhen(System.currentTimeMillis())
		.setContentIntent(theappIntent)
		.build();
		
		playSound(Uri.parse(mRingTone));
	
		if (vibrate == 1) {
			vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
			long[] pattern = {200, 2000, 100, 1700, 200, 2000, 100, 1700, 200, 2000, 100, 1700};
			vibe.vibrate(pattern, 2);
		}
		nm.notify(12345, notifi);
	}

	private void playSound(Uri alert) {
		if (mMediaPlayer != null) return;
		
		mMediaPlayer = new MediaPlayer();
		try {
			mMediaPlayer.setDataSource(this, alert);
			final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
			if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mMediaPlayer.prepare();
				mMediaPlayer.setLooping(true);
				mMediaPlayer.start();
			}
		} catch (IOException e) {}
	}

}
